package tmt.usercenter.web.plugin.filesevice;

import com.tmt.datatable.editor.IFileDataHolder;
import com.tmt.fileservice.IFileDataResolver;
import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.util.Base64;
import java.util.UUID;

/**
 * Created by Stark on 2017/6/29.
 */
public class Base64DataResolver implements IFileDataResolver, IFileDataHolder {

    private String base64Str;

    private String fieldName;

    private String fileName;

    public Base64DataResolver() {
    }

    public Base64DataResolver(String base64Str) {
        this.base64Str = base64Str;
    }

    @Override
    public String getFileType() {
        return "jpg";
    }

    @Override
    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
        this.fileName = UUID.randomUUID().toString() + "_" + this.fieldName + "." + getFileType();
    }

    @Override
    public void setFileData(Object fileData) {
        base64Str = (String) fileData;
    }

    @Override
    public String getFieldName() {
        return this.fieldName;
    }

    @Override
    public String getFileName() {
        return this.fileName;
    }

    @Override
    public Long getFileLength() {
        return Long.parseLong("" + base64Str.length());
    }

    @Override
    public void transferTo(File file) throws IOException {
        ByteArrayInputStream is = convertBase64ToStream(base64Str);
        OutputStream os = new FileOutputStream(file);
        FileCopyUtils.copy(is, os);
    }

    @Override
    public void validate(Class<?> clazz, String propName) throws Exception {

    }

    @Override
    public IFileDataHolder newInstance() {
        return new Base64DataResolver();
    }

    /**
     * @param base64Str
     * @return
     * @throws IOException
     */
    private static ByteArrayInputStream convertBase64ToStream(String base64Str) throws IOException {
        String imageString = base64Str.substring(base64Str.indexOf(",") + 1);
        byte[] imageByte = Base64.getDecoder().decode(imageString);
        return new ByteArrayInputStream(imageByte);
    }
}
